package com.m3958.firstgwt.server.ftpserver;

import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.usermanager.impl.WriteRequest;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.assistedinject.Assisted;
import com.m3958.firstgwt.server.dao.WebSiteDao;

public class MyWritePermission implements Authority{
	
	@Inject
	private Injector injector;
	
	private User user;
	
	@Inject
	public MyWritePermission(@Assisted User user){
		this.user = user;
	}

	@Override
	public boolean canAuthorize(AuthorizationRequest request) {
		return request instanceof WriteRequest;
	}

	@Override
	public AuthorizationRequest authorize(AuthorizationRequest request) {
		if (request instanceof WriteRequest) {
			WriteRequest wr = (WriteRequest) request;
			String fp = wr.getFile();
			String[] ds = fp.split("/");
			if(ds.length < 4){
				return null;
			}
	    	WebSiteDao wdao = injector.getInstance(WebSiteDao.class);
	    	if(wdao.hasFtpPermission(user.getName(), ds[1])){
	    		return wr;
	    	}else{
	    		return null;
	    	}
		}else{
			return null;
		}
	}

}
